﻿var toolbox = function() {
    /*
    Toolbox.js library that permits to generate toolboxes for each field customization
    */
    var lastShowToolbox = null;
    /*
    Resulting CSS properties in JSON format
    */
    var formCSS = { "ids": [],
        "tags": [],
        "classes": []
    };

    return {
        /*
        Add element to property grid generating field adn label
        Params:
        target          Target field of grid
        propertyName    name of property
        type            Type of property ( Text only for now )
        Returns:
        <li> Node conteining label and field with onblur listener, field id is generated by propertyName+target 
    		
	    Example of generated node:
        <li>
        <label for="border-widthPhone">border-width</label>
        <input id="border-widthPhone" type="text" onblur="applyChanges('Phone','border-width',this.value,'size' );"/>
        </li>
        */
        addPropertyGridElement: function(target, propertyName, validator, info) {

            // Creating wrapper for grid element
            var container = document.createElement('li');

            // Generating label+input field
            var label = document.createElement('label');

            switch (propertyName) {
                case "border-style":
                    {
                        var field = this.generateComboBox(['Solid', 'Dashed', 'Dotted']);

                        field.setAttribute('id', propertyName + target);
                        field.setAttribute('title', info);

                        field.setAttribute('onchange', "toolbox.applyChanges('" + target + "','" + propertyName + "',this.value,'" + validator + "' );");
                        break;
                    }
                case "font-family":
                    {
                        var field = this.generateComboBox(['Verdana', 'Arial', 'Sans-Serif', 'Comic Sans MS']);

                        field.setAttribute('id', propertyName + target);
                        field.setAttribute('title', info);

                        field.setAttribute('onchange', "toolbox.applyChanges('" + target + "','" + propertyName + "',this.value,'" + validator + "' );");
                        break;
                    }
                case "text-decoration":
                    {
                        var field = this.generateComboBox(['none', 'underline', 'line-through', 'overline', 'blink']);
                        field.setAttribute('id', propertyName + target);
                        field.setAttribute('title', info);

                        field.setAttribute('onchange', "toolbox.applyChanges('" + target + "','" + propertyName + "',this.value,'" + validator + "' );");
                        break;
                    }
                default:
                    {
                        // No special threatment requiered
                        var field = document.createElement('input');

                        field.setAttribute('id', propertyName + target);
                        field.setAttribute('type', 'text');
                        field.setAttribute('title', info);
                        // Adding handler to the field
                        field.setAttribute('onblur', "toolbox.applyChanges('" + target + "','" + propertyName + "',this.value,'" + validator + "' );");
                    }
            }

            // Color fields
            if (validator == "color") {
                field.setAttribute('class', "gccolor");
                
            }

            label.setAttribute('for', propertyName + target);
            label.appendChild(document.createTextNode(propertyName));

            if ($('#' + target).css(propertyName) != undefined) {
                if (validator == "color")
                    field.setAttribute('value', RGBtoHex($('#' + target).css(propertyName) ));
                else
                    field.setAttribute('value', $('#' + target).css(propertyName));
            }
            // Wrapping all in <li> container
            container.appendChild(label);
            container.appendChild(field);
            return container;
        },

        generatePropertyGrid: function(id, type) {
            /* Generate only is not exists, else just show*/
            var elem;
            var propertyList;
            if (lastShowToolbox != null) {
                lastShowToolbox.setAttribute("style", "display:none");
            }
            if (elem = document.getElementById(id + 'ToolBox')) {
                if (lastShowToolbox == elem) {
                    elem.setAttribute("style", "display:none");
                    lastShowToolbox = null;
                } else {
                    elem.setAttribute("style", "display:block");
                    lastShowToolbox = elem;
                }
            } else {
                var toolbox = document.createElement('div');
                var title = document.createElement('h3');
                var groupForm = document.createElement('form');

                var checkbox = document.createElement('input');
                var checkboxLabel = document.createElement('label');

                groupForm.setAttribute('id', id + 'Form');

                toolbox.setAttribute('id', id + 'ToolBox');
                toolbox.setAttribute('class', 'toolbox');

                title.appendChild(document.createTextNode("Field Customization ( Type: " + type + " )"));

                var closeIcon = document.createElement('a');
                closeIcon.appendChild(document.createTextNode('Close'));
                closeIcon.setAttribute('class', 'closeLink');
                closeIcon.setAttribute('onclick', 'toolbox.lastShowToolbox=null;this.parentNode.setAttribute("style", "display:none");');

                toolbox.appendChild(title);
                toolbox.appendChild(closeIcon);
                // Default text field
                propertyList = PropertyList.getList(type);

                // Cycling though property groups 
                for (i = 0; i < propertyList.length; i++) {
                    // Creating title for each group
                    var groupTitle = document.createElement('h4');
                    groupTitle.appendChild(document.createTextNode(propertyList[i].group));

                    var groupGrid = document.createElement('ul');

                    // Cycling though avaible properties for that group
                    for (j = 0; j < propertyList[i].properties.length; j++) {
                        elem = propertyList[i].properties[j];
                        groupGrid.appendChild(this.addPropertyGridElement(id, elem.name, elem.validator, elem.info));
                    }
                    // Assembling properties group node

                    groupForm.appendChild(groupTitle);
                    groupForm.appendChild(groupGrid);
                }
                toolbox.appendChild(groupForm);

                checkbox.setAttribute('id', id + 'ApplyToID');
                checkbox.setAttribute('type', 'checkbox');

                checkboxLabel.setAttribute('for', id + 'ApplyToID');
                checkboxLabel.appendChild(document.createTextNode("Apply to this"));

                toolbox.appendChild(checkbox);
                toolbox.appendChild(checkboxLabel);
                // Appending Property grid to placeholder div named "grid"+FieldId
                document.getElementById('grid' + id).appendChild(toolbox);

                $('#grid' + id + ' input.gccolor').gccolor({
                    onChange: function(target, color) { target.val('#' + color); $(target).trigger('onblur'); }
                });
                lastShowToolbox = toolbox;
                //Adding tooltips		
                //$('#' + id + 'Form > ul > li > input').tooltips();


            }
        },

        /*
        Add changes already made to the formCss
        Params: 
        targetType      Class , ID 
        target          Class name, ID name
        property        Name of property to modify
        value           value of propery to set
        */
        addChanges: function(targetType, target, property, value) {
            var propList;
            if (targetType == '.')
                propList = eval('formCSS.classes');
            else if (targetType == '#')
                propList = eval('formCSS.ids');
            else
                return false;
            //$(targetType + target).attr('value', value);
            // Searching if element is already present in customziation list    
            for (i = 0; (i < propList.length) && (propList[i].target != target); i++) { }
            // No css yet defined for this field
            if (i == propList.length) {
                propList.push(
                { "target": target,
                    "properties": [{
                        "property": property,
                        "value": value
}]
                    });
                    return true;
                }
                var overwriten = false;
                // Looking it that property was already set
                for (j = 0; j < propList[i].properties.length; j++) {
                    // Overwrite existing value
                    if (propList[i].properties[j].property == property) {
                        propList[i].properties[j].value = value;
                        overwriten = true;
                        return;
                    }
                }
                // New property case
                if (!overwriten) {
                    propList[i].properties.push({ "property": property, "value": value });
                }
                return true;
            },

            /*
            Apply changes to element runtime
            Params: 
            target          Trarget of changes id, class, type
            property        Name of property to modify
            value           value of propery to set
            */
            applyChanges: function(target, property, value, validator) {
                if (!value)
                    return false;
                if (!PropertyList.validate(validator, value)) {
                    alert(value + " is invalid " + validator);
                    return false;
                }

                var i = 0;
                var elem = document.getElementById(target);

                var propList = eval('formCSS.ids');

                if (document.getElementById(target + 'ApplyToID') && document.getElementById(target + 'ApplyToID').checked == false) {
                    var insideContentHome = false;
                    var regex = new RegExp("ctl00_contentHome[._]*");
                    if (regex.test(target))
                        insideContentHome = true;


                    propList = eval('formCSS.classes');
                    if (insideContentHome) {
                        target = $("#" + target).attr("rel");
                        $("#ctl00_contentHome_presenPanel [rel='" + target + "']").css(property, value);
                    }
                    else
                        $("#ctl00_contentHome_presenPanel [class='" + target + "']").css(property, value);

                } else {
                    if (target == 'presenPanel') {
                        $('#ctl00_contentHome_' + target).css(property, value);

                    }
                    else
                        $('#' + target).css(property, value);
                }
                // Searching if element is already present in customziation list
                for (i = 0; (i < propList.length) && (propList[i].target != target); i++) { }
                // No css yet defined for this field
                if (i == propList.length) {
                    propList.push(
                { "target": target,
                    "properties": [{
                        "property": property,
                        "value": value
}]
                    });
                    return true;
                }
                var overwriten = false;
                // Looking it that property was already set
                for (j = 0; j < propList[i].properties.length; j++) {
                    // Overwrite existing value
                    if (propList[i].properties[j].property == property) {
                        propList[i].properties[j].value = value;
                        overwriten = true;
                        return;
                    }
                }
                // New property case
                if (!overwriten) {
                    propList[i].properties.push({ "property": property, "value": value });
                }
                return true;
            },

            /*
            Generates final CSS 
            Params:
            element         Element to apply property
            property        Property to store
            value           Value of property to store
            */
            generateCSS: function() {
                var i;
                var elem;
                var css = "";
                for (i = 0; i < formCSS.classes.length; i++) {
                    elem = formCSS.classes[i].target;

                    css += "." + elem + "{\n";
                    for (j = 0; j < formCSS.classes[i].properties.length; j++) {
                        css += formCSS.classes[i].properties[j].property + ":" + formCSS.classes[i].properties[j].value + ";\n";
                    }
                    css += "}\n"
                }
                for (i = 0; i < formCSS.ids.length; i++) {
                    elem = formCSS.ids[i].target;

                    // TO CHANGE
                    var espressione = new RegExp("^ctl00_contentHome[._-]*");
                    var match = espressione.test(elem);
                    //alert(elem + ' ' + match);
                    if (!match)
                        elem = "#ctl00_contentHome_ctl01_" + elem;
                    else
                        elem = "#" + elem;
                    //alert(elem);
                    css += elem + "{\n";
                    for (j = 0; j < formCSS.ids[i].properties.length; j++) {
                        css += formCSS.ids[i].properties[j].property + ":" + formCSS.ids[i].properties[j].value + ";\n";
                    }
                    css += "}\n"
                }
                return css;
            },
            generateComboBox: function(options) {
                var i;
                var field = document.createElement('select');
                var choice;

                for (i = 0; i < options.length; i++) {
                    choice = document.createElement('option');
                    choice.value = options[i];
                    choice.appendChild(document.createTextNode(options[i]));
                    field.appendChild(choice);
                }
                return field;
            }
        };
    } ();